package com.brillilab.starter.controller.aio.kit;

import com.brillilab.common.entity.ResponseVo;
import com.brillilab.domain.po.global.GlobalKit;
import com.brillilab.domain.po.method.Method;
import com.brillilab.service.core.global.IGlobalKitService;
import com.brillilab.service.core.method.IMethodService;
import com.brillilab.service.logic.user.UsersLogic;
import com.brillilab.starter.constant.StarterConstant;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/globalKit")
public class GlobalKitController {

    @Resource
    private IGlobalKitService globalKitService;

    @Resource
    private IMethodService methodService;

    @Resource
    private UsersLogic usersLogic;

    @RequestMapping(value = "create",method = RequestMethod.GET)
    public ResponseVo createGlobalKitRelateMethod(@RequestHeader(name = StarterConstant.TOKEN) String token){
        usersLogic.getUserByToken(token);
        List<GlobalKit> kits =globalKitService.selectTopNoMethodKit();
        if (CollectionUtils.isNotEmpty(kits)){
            List<Method> methods = kits.stream().map(e -> {
                Method method = new Method();
                method.setName(e.getName());
                method.setMethodTypeId(9L);
                method.setAuthor("BioLegend");
                method.setFromType(2);
                method.setCurrent(1);
                method.setVersion(0);
                method.setOnStock(0);
                return method;
            }).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(methods)){
                methods = methodService.insertBatch(methods);
                methods.forEach(m -> {
                    m.setSourceMethodId(m.getId());
                    m.setInitMethodId(m.getId());
                    kits.forEach(k ->{
                        if (k.getName().equals(m.getName())){
                            k.setRelateMethodId(m.getId());
                        }
                    });
                });

                methodService.updateInitInfo(methods);
                globalKitService.updateRelateInfo(kits);
            }
        }
        return ResponseVo.success();
    }

}
